package cn.whx.hrm.service.impl;

import cn.whx.hrm.LoginUserConstant;
import cn.whx.hrm.domain.Employee;
import cn.whx.hrm.domain.LoginUser;
import cn.whx.hrm.domain.Tenant;
import cn.whx.hrm.dto.EnteringDto;
import cn.whx.hrm.feign.LoginUserFeignClient;
import cn.whx.hrm.mapper.EmployeeMapper;
import cn.whx.hrm.mapper.TenantMapper;
import cn.whx.hrm.query.TenantQuery;
import cn.whx.hrm.service.ITenantService;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whx
 * @since 2021-06-17
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    //注入feign对象
    private LoginUserFeignClient loginUserFeignClient;

    @Override
    public AjaxResult loadPageList(TenantQuery query) {
        //搞个分页对象
        Page<Tenant> page = new Page<Tenant>(query.getPage(),query.getRows());
        //查询列表
        List<Tenant> list =  tenantMapper.loadPageList(query,page);
        //将查询的列表结果封装成一个分页对象
        PageList<Tenant> pageList = new PageList<>(page.getTotal(), list);
        //最后返回
        return AjaxResult.me().setResultObj(pageList);
    }

    @Override
    public AjaxResult entering(EnteringDto dto) {
        //保存套餐
        LoginUser loginUser = new LoginUser();
        //获取员工进行封装
        Employee employee = dto.getEmployee();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        loginUser.setType(LoginUserConstant.LOGIN_USER_ADMIN);
        loginUser.setMealId(dto.getMealId());
        AjaxResult result = loginUserFeignClient.addOrUpdate(loginUser);
        if (!result.isSuccess()){
            throw new RuntimeException("套餐保存错误");
        }
        //保存loginuserid
        Integer id = (Integer) result.getResultObj();
        Long loginUserId = Long.valueOf(id);
        //保存机构的信息
        Tenant tenant = dto.getTenant();
        tenant.setRegisterTime(new Date());
        tenantMapper.insert(tenant);
        //保存管理员的信息
        employee.setTenantId(tenant.getId());
        employee.setInputTime(new Date());
        employee.setType(LoginUserConstant.LOGIN_GENERAL_ADMIN);
        employee.setLoginId(loginUserId);
        employee.setState(0);
        employeeMapper.insert(employee);//保存

        return AjaxResult.me();
    }
}
